<?php

namespace App\Services;

use App\Models\GameChannel;
use App\Models\UserAccountBindChannel;
use App\Models\UserHutong;
use App\Services\JuheH5\AccountService;

class UserHutongService extends ServiceBase
{
    /**
     * 将渠道账号绑定到某个user_id上
     *
     * @param int $user_id
     * @param int $game_id
     * @param int $channel
     * @param string $channel_openid 渠道账号openid
     * @param string $account_openid 官方账号openid
     * @return UserHutong
     */
    public function getOrCreateHutong($user_id, $game_id, $channel, $channel_openid='', $account_openid=''): UserHutong
    {
        if (!empty($channel_openid)) {
            $query = UserHutong::where('channel_openid', $channel_openid);
        } else {
            $query = UserHutong::where('account_openid', $account_openid);
        }
        $hutong = $query->whereRaw("game_id={$game_id} AND channel={$channel}")->first();
        if ($hutong) {
            return $hutong;
        }

        $hutong = new UserHutong;
        $hutong->create_time = time();
        $hutong->game_id = $game_id;
        $hutong->channel = $channel;
        $hutong->channel_openid = $channel_openid;
        $hutong->account_openid = $account_openid;
        $hutong->user_id = $user_id;
        $hutong->save();

        return $hutong;
    }

    public function getByChannelOpenid($game_id, $channel, $channel_openid)
    {
        $hutong = UserHutong::whereRaw("channel_openid='{$channel_openid}' AND game_id={$game_id} AND channel={$channel}")->first();
        return $hutong;
    }

    public function getByAccountOpenid($game_id, $channel, $account_openid)
    {
        $hutong = UserHutong::whereRaw("account_openid='{$account_openid}' AND game_id={$game_id} AND channel={$channel}")->first();
        return $hutong;
    }

    /**
     * 根据渠道和渠道openid，创建官方账号绑定关系
     *
     * @param int $channel
     * @param string $channel_openid
     * @return void|UserAccountBindChannel
     */
    public function getOrCreateAccountBind($channel, $channel_openid)
    {
        $bind = UserAccountBindChannel::where('channel_openid', $channel_openid)->where('channel', $channel)->first();
        if ($bind) {
            return $bind;
        }

        $res = AccountService::getInstance()->fastReg();
        if (!$res) {
            return;
        }

        $bind = new UserAccountBindChannel;
        $bind->create_time = time();
        $bind->channel = $channel;
        $bind->channel_openid = $channel_openid;
        $bind->account_openid = $res['openid'];
        $bind->save();

        return $bind;
    }

    public function getBindByAccount($channel, $account_openid)
    {
        return UserAccountBindChannel::where('account_openid', $account_openid)->where('channel', $channel)->first();
    }
}
